var Shop = function()
{
    this.idAutoComplete = 'autocomplete';
    this.idListAutoComplete = 'listautocomplete';
    this.idImageFolders = 'image_folders';
    this.idListImages = 'list_images';
    this.idShowImage = 'showimage';
    this.divProductOptions = 'product_options';
    this.divRelated = 'relateds';
    this.idGroups = 'groups';
    this.idProductList = 'prodlist';
    //this.idProductslink = 'productlink';
    this.idViewPage = 'viewpage';
    this.formAddProduct = 'add_product';
    this.idSubmitForm = 'submitform';
    this.idMessage = 'message';
    this.idBrandsAutoComplete = 'brandsautocomplete';
    this.idFilterProduct = 'filterproduct';
    this.messageForShowImage = '';
    //this.idTax = 'tax';
    this.countRelated = 3;
    this.countOptions = 3;
    this.separate = '###';
    this.webSiteUrl = '';
    this.products = '';
    this.brands = '';
}
/*** init method ***/
Shop.prototype.init = function(params)
{
    this.webSiteUrl = params.websiteurl ? params.websiteurl : '';
    //this.getProducts();
    document.getElementById(this.idAutoComplete).addEventListener('focus', function() {shop.getProducts();}, false);
    document.getElementById(this.idAutoComplete).addEventListener('keyup', function() {shop.autoComplete(this);}, false);
    document.forms[this.formAddProduct].brand.addEventListener('focus', function() {shop.getBrands();}, false);
    document.forms[this.formAddProduct].brand.addEventListener('keyup', function() {shop.autoCompleteBrand(this);}, false);
    document.onclick = function() {
        document.getElementById(shop.idListAutoComplete).style.display = 'none';
        document.getElementById(shop.idBrandsAutoComplete).style.display = 'none';
    };
    this.messageForShowImage = document.getElementById(this.idShowImage).innerHTML;
}
/***  method using for ajax query ***/
Shop.prototype.ajax = function(params)
{
    var type = 'GET';
    var url = '';
    var async = true;
    var data = null;
    var dataType = 'html';
    if (params.type && params.type.toUpperCase() == 'POST') {
        type = params.type.toUpperCase()
    }
    if (params.url) {
        url = params.url;
    }
    if (params.data && typeof(params.data) == 'object') {
        data = '';
        for (var i in params.data) {
            var str = params.data[i].toString();
            var query = str.replace(/(&)/g, '');
            data += i+'='+query+'&';
            //data += i+'='+params.data[i]+'&';
        }
    }
    if (params.dataType) {
        dataType = params.dataType;
    }
    if (params.async == false) {
        async = false;
    }
    var req;
    try {req = new XMLHttpRequest();}
    catch (e) {
        try {req = new ActiveXObject("Msxml2.XMLHTTP");}
        catch (e) {
            try {req = new ActiveXObject("Microsoft.XMLHTTP");}
            catch (e) {return;}
        }
    }
    req.open(type, url, async);
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            if (req.status == 200) {
                if (params.success) {
                    params.success(req.responseText, req.status);
                }
            }else {
                if (params.error) {
                    params.error(req.statusText, req.status);
                }
            }
        }
    }
    if (type == 'POST') {
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    } else {
        req.setRequestHeader('Content-Type', 'text/'+dataType+'');
    }
    req.setRequestHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT');
    req.setRequestHeader('Pragma', 'no-cache');
    req.send(data);
}
/*** method gets products ***/
Shop.prototype.getProducts = function()
{
    if (this.products == '' || this.products.length == 0) {
        this.ajax({
            type : 'POST',
            url : this.webSiteUrl+'sys/backend_shopping/productsforautocomplete/',
            success : function(data) {
                shop.products = data.split(shop.separate);
            }
        });
    }
}
/*** method add product by product array ***/
Shop.prototype.addProductByProducts = function(data)
{
    this.products[this.products.length-1] = data;
}
/*** method loads images for selected folder and shows 'div' with those images ***/
Shop.prototype.loadImages = function(folder)
{
    if (folder == '') {return;}
    this.ajax({
        type : 'POST',
        url : this.webSiteUrl+'sys/backend_shopping/loadimages/',
        data : {folder : folder},
        success : function(data) {
            var obj = eval('('+data+')');
            var elm = document.getElementById(shop.idListImages);
            elm.innerHTML = obj.small;
            /*elm.style.display = 'block';*/
            $(elm).show('700');
        }
    });
}
/*** method shows selected image and adds url of image in the form ***/
Shop.prototype.selectImage = function(src)
{
    var elm = document.getElementById(this.idShowImage);
    var img = new Image();
    img.onload = function () {
        elm.innerHTML = '';
        elm.appendChild(img);
    };
    img.src = src;
    var ie = (document.all && !window.opera);
    if (ie) {
        if (img.width > 140) {
            img.width = 140;
        }
        if (img.height > 130) {
            img.height = 130;
        }
    }
    document.getElementById(this.idListImages).style.display = 'none';
    document.forms[this.formAddProduct].image.value = src.replace(this.webSiteUrl, '');
}
/*** method adds options for product ***/
Shop.prototype.addOption = function()
{
    var children = document.getElementById(this.divProductOptions).childNodes;
    var counter = 0;
    for (var i=0; i<children.length; i++) {
        if (children.item(i).nodeName == "P") {
            counter++;
        }
    }
    if (counter < this.countOptions) {
        this.addElementOption('', '');
    }
}
/*** method adds options for product into html page ***/
Shop.prototype.addElementOption = function(key, val)
{
    var p = document.createElement('p');
    var del = document.createElement('img');
    del.setAttribute('title', 'delete this option');
    del.setAttribute('alt', 'delete option');
    del.setAttribute('onclick', 'this.parentNode.parentNode.removeChild(this.parentNode);');
    del.setAttribute('src', this.webSiteUrl+'system/images/ico_del_green.gif');
    var input1 = document.createElement('input');
    input1.setAttribute('type', 'text');
    input1.setAttribute('value', key);
    var input2 = document.createElement('input');
    input2.setAttribute('type', 'text');
    input2.setAttribute('value', val);
    p.appendChild(del);p.innerHTML += ' ';
    p.appendChild(input1);p.innerHTML += ' ';
    p.appendChild(input2);
    document.getElementById(this.divProductOptions).appendChild(p);
}
/*** method adds related products into html page ***/
Shop.prototype.addElementRelated = function(name, img, id)
{
    var p = document.createElement('p');
    p.setAttribute('id', 'related-'+id);
    var del = document.createElement('img');
    del.setAttribute('style', 'cursor:pointer;position:absolute;top:0px;right:0px;width:12px;height:12px;');
    del.setAttribute('src', this.webSiteUrl+'system/images/ico_del_green.gif');
    del.setAttribute('onclick', 'this.parentNode.parentNode.removeChild(this.parentNode);');
    del.setAttribute('title', 'delete');
    var elmImg = document.createElement('img');
    elmImg.setAttribute('src', img);
    elmImg.setAttribute('style', 'max-width:110px;');
    var span = document.createElement('span');
    span.style.display = 'block';
    span.setAttribute('title', name );
    span.innerHTML = name.substr(0,40);
    p.appendChild(elmImg);p.innerHTML += ' ';
    p.appendChild(del);p.innerHTML += ' ';
    p.appendChild(span);
    document.getElementById(this.divRelated).appendChild(p);
}
/*** method finds product for 'autocomplete' ***/
Shop.prototype.autoComplete = function(elm)
{
    var val = elm.value;
    val = val.replace(/^\s+/g,'');
    val = val.replace(/\s+$/g,'');
    var ul = document.getElementById(this.idListAutoComplete);
    ul.innerHTML = '';
    ul.style.display = 'none';
    if (val == '') {return;}
    for (var i in this.products) {
        var pair = this.products[i].split(':::');
        var index = pair[0].toLowerCase().indexOf(val.toLowerCase());
        if (index == 0) {
            var li = document.createElement('li');
            li.setAttribute('id', 'prodautocomplete-'+pair[2]);
            li.setAttribute('style', 'overflow:hidden;border-bottom:1px dotted #eee; padding:4px;');
            var img = document.createElement('img');
            img.setAttribute('src', this.webSiteUrl+pair[1]);
            img.setAttribute('border', '0');
            img.setAttribute('style', 'max-width:50px;float:left;padding:2px 5px 2px 0px;');
            li.appendChild(img);
            li.innerHTML += ' ';
            var span = document.createElement('span');
            span.setAttribute('title', pair[0]);
            span.innerHTML = pair[0]+"&nbsp; id="+pair[3];
            li.appendChild(span);
            li.onclick = function() {
                var list = document.getElementById(shop.divRelated);
                var counter = 0;
                for (i=0; i<list.childNodes.length; i++) {
                    if (list.childNodes.item(i).nodeName == 'P') {
                        counter++;
                    }
                }
                if (counter < shop.countRelated) {
                    var id = this.id.split('-')[1];
                    var name = this.childNodes.item(2).title;
                    var img = this.childNodes.item(0).src;
                    shop.addElementRelated(name, img, id);
                }
                document.getElementById(shop.idAutoComplete).value = '';
            };
            ul.appendChild(li);
        }
    }
    if (ul.childNodes.length > 0) {
	ul.style.display = 'block';     
    }
}
/*** add group ***/
Shop.prototype.addGroup = function(name)
{
    name = name.replace(/^\s+/g,'');
    name = name.replace(/\s+$/g,'');
    if (name == '') {return;}
    this.ajax({
        type : 'POST',
        url : this.webSiteUrl+'sys/backend_shopping/addgroup/',
        data : {group : name},
        success : function(data) {
            var obj = eval('('+data+')');
            if (obj.exist) {alert('This group exist.');return;}
            if (obj.save) {
                shop.addElementGroup(obj.id, name);
            }
        }
    });
}
/*** add element group into html ***/
Shop.prototype.addElementGroup = function(id, name)
{
    var input = document.createElement('input');
    input.setAttribute('type', 'checkbox');
    var img = document.createElement('img');
    img.setAttribute('title', 'delete '+name);
    img.setAttribute('onclick', "if(confirm('Do you really want to delete this category?')){shop.deleteGroup('"+id+"');}");
    img.setAttribute('src', this.webSiteUrl+'system/images/ico_delete.gif');
    var span = document.createElement('span');
    span.setAttribute('title', name);
    span.innerHTML = name.substr(0,11);
    var p = document.createElement('p');
    p.setAttribute('id', 'group-'+id);
    p.appendChild(input);p.innerHTML += ' ';
    p.appendChild(img);p.innerHTML += ' ';
    p.appendChild(span);
    document.getElementById(this.idGroups).appendChild(p);
}
/*** delete group ***/
Shop.prototype.deleteGroup = function(id)
{
    if (!/^([0-9]{1,10})$/.test(id)) {return;}
    this.ajax({
        type : 'POST',
        url : this.webSiteUrl+'sys/backend_shopping/deletegroup/',
        data : {id : id},
        success : function(data) {
            var obj = eval('('+data+')');
            if (obj.del) {
                var elm = document.getElementById('group-'+id);
                elm.parentNode.removeChild(elm);
            }
        }
    });
}
/*** reset all checkbox for groups ***/
Shop.prototype.resetGroupsCheckbox = function()
{
    var groups = document.getElementById(this.idGroups).childNodes;
    for (var i=0; i<groups.length; i++) {
        if (groups.item(i).nodeName == 'P') {
            if (groups.item(i).childNodes.item(0).checked) {
                groups.item(i).childNodes.item(0).checked = false;
            }
        }
    }
}
/*** reset all value for form 'addproduct' ***/
Shop.prototype.resetFormAddProduct = function() 
{
    var elm = document.getElementById('prodlist');
    elm.style.display = 'none';
    document.getElementById(this.idImageFolders).options[0].selected = true;
    document.getElementById(this.idShowImage).style.border = '0';
    document.getElementById(this.idShowImage).innerHTML = this.messageForShowImage;
    document.getElementById(this.idViewPage).style.display = 'none';
    document.getElementById(this.idViewPage).childNodes.item(1).href = '#';
    document.forms[this.formAddProduct].name.style.border = '1px solid #7c7c7c';
    document.forms[this.formAddProduct].item_id.style.border = '1px solid #7c7c7c';
    document.forms[this.formAddProduct].price.style.border = '1px solid #7c7c7c';
    document.forms[this.formAddProduct].weight.value = '';
    document.forms[this.formAddProduct].tax.value = 0;
    document.forms[this.formAddProduct].brand.value = '';
    document.forms[this.formAddProduct].image.value = '';
    document.forms[this.formAddProduct].id.value = 0;
    document.forms[this.formAddProduct].reset();
    document.getElementById('producttodel').value = '';
    document.getElementById(this.divProductOptions).innerHTML = '';
    this.addOption();
    document.getElementById(this.divRelated).innerHTML = '';
    this.resetGroupsCheckbox();
    document.getElementById(this.idSubmitForm).setAttribute('onclick', 'shop.addProduct();');
}
/*** method returns options for product ***/
Shop.prototype.getOptions = function()
{
    var options = '';
    var listOptions = document.getElementById(this.divProductOptions).childNodes;
    for (var i=0; i<listOptions.length; i++) {
        if (listOptions.item(i).nodeName == "P") {
            var key = listOptions.item(i).childNodes.item(2).value;
            var val = listOptions.item(i).childNodes.item(4).value;
            key = key.replace(/^\s+/g,'');key = key.replace(/\s+$/g,'');
            val = val.replace(/^\s+/g,'');val = val.replace(/\s+$/g,'');
            if (key != '') {
                options += key+':::';
                options += val+this.separate;
            }
		
        }
    }
    return options;
}
/*** method returns related for product (return name of product)***/
Shop.prototype.getRelated = function()
{
    var related = '';
    var listRelated = document.getElementById(this.divRelated).childNodes;
    for (var i=0; i<listRelated.length; i++) {
        if (listRelated.item(i).nodeName == 'P') {
            var id = listRelated.item(i).id.split('-')[1];
             if (/^([0-9]{1,10})$/.test(id) && id > 0) {
                related += id+',';
             }
        }
    }
    return related;
}
/*** method returns groups for product (return id of group) ***/
Shop.prototype.getGroups = function()
{
    var groups = '';
    var listGroups = document.getElementById(this.idGroups).childNodes;
    for (var i=0; i<listGroups.length; i++) {
        if (listGroups.item(i).nodeName == 'P') {
            if (listGroups.item(i).childNodes.item(0).checked) {
                var id = listGroups.item(i).id.split('-')[1];
                if (/^([0-9]{1,10})$/.test(id) && id > 0) {
                    groups += id+',';
                }
            }
        }
    }
    return groups;
}
/*** method sets options ***/
Shop.prototype.setOptions = function(data)
{
    document.getElementById(this.divProductOptions).innerHTML = '';
    var options = data.split(this.separate);
    for (var o in options) {
        var pair = options[o].split(':::');
        if (pair[0] != '') {
            this.addElementOption(pair[0], pair[1]);
        }
    }
}
/*** method sets related  ***/
Shop.prototype.setRelated = function(data)
{
    document.getElementById(this.divRelated).innerHTML = '';
    var related = data.split(',');
    for (var r in related) {
        if (parseInt(related[r])  > 0) {
            for (var i in this.products) {
                var pair = this.products[i].split(':::');
                if (parseInt(pair[2]) == parseInt(related[r])) {
                    this.addElementRelated(pair[0], this.webSiteUrl+pair[1], pair[2]);
                    break;
                }
            }
        }
    }
}
/*** method sets groups  ***/
Shop.prototype.setGroups = function(data)
{
    this.resetGroupsCheckbox();
    var groups = data.split(',');
    var listGroups = document.getElementById(this.idGroups).childNodes;
    for (var i=0; i<listGroups.length; i++) {
        if (listGroups.item(i).nodeName == 'P') {
            var tmp = listGroups.item(i).id.split('-');
            for (var g in groups) {
                if (groups[g] > 0 && groups[g] == tmp[1]) {
                    listGroups.item(i).childNodes.item(0).checked = true;
                }
            }
        }
    }
}
/*** method checks form 'add_product' ***/
Shop.prototype.checkFormAddProduct = function()
{
    var ltrim = /^\s+/g, rtrim = /\s+$/g;
    var form = document.forms[this.formAddProduct];
    var name = form.name.value;
    var item_id = form.item_id.value;
    var price = form.price.value;
    var description = form.description.value;
    var image = form.image.value;
    
    name = name.replace(ltrim,'');name = name.replace(rtrim,'');
    item_id = item_id.replace(ltrim,'');item_id = item_id.replace(rtrim,'');
    description = description.replace(ltrim,'');description = description.replace(rtrim,'');
    image = image.replace(ltrim,'');image = image.replace(rtrim,'');
    
    var errors = new Array();
    if (name == '') {
        errors.push(1);form.name.style.border = '1px solid red';
    } else {
        form.name.style.border = '1px solid #7C7C7C';
    }
    if (item_id == '') {
        errors.push(1);form.item_id.style.border = '1px solid red';
    } else {
        form.item_id.style.border = '1px solid #7C7C7C';
    }
    if (!/^([0-9.]{1,10})$/.test(price)) {
        errors.push(1);form.price.style.border = '1px solid red';
    } else {
        form.price.style.border = '1px solid #7C7C7C';
    }
    if (image == '') {
        errors.push(1);document.getElementById(this.idShowImage).style.border = '1px solid red';
    } else {
        document.getElementById(this.idShowImage).style.border = '1px solid #7C7C7C';
    }
    if (errors.length > 0) {
        return false;
    }
    return true;
}
/*** method adds new product ***/
Shop.prototype.addProduct = function()
{
    if (!this.checkFormAddProduct()) {return;}
    var options = this.getOptions();
    var related = this.getRelated();
    var groups = this.getGroups();
    var form = document.forms[this.formAddProduct];
    var msg = document.getElementById(this.idMessage);
    this.ajax({
        type : 'POST',
        url : this.webSiteUrl+'sys/backend_shopping/addproduct/',
        data : {name:form.name.value, item_id:form.item_id.value, price:form.price.value, weight:form.weight.value, tax:form.tax.options[form.tax.selectedIndex].value, photo:form.image.value,
            brand:form.brand.value, desc:form.description.value, options:options, related:related, groups:groups},
        success : function(data) {
            var obj = eval('('+data+')');
            if (obj.id > 0 ) {
                shop.addProductByProducts(form.name.value+':::'+form.image.value+':::'+obj.id);
                var prodName = form.name.value;
                var prodItemId = form.item_id.value;
                prodName = prodName.replace(/^\s+/g,'');prodName = prodName.replace(/\s+$/g,'');
                prodItemId = prodItemId.replace(/^\s+/g,'');prodItemId = prodItemId.replace(/\s+$/g,'');
		var templateProduct = '<li class="shoproductlisting" id="'+obj.id+'">';
		templateProduct += '<a href="#" onclick="shop.getDataProductForForm('+obj.id+');">';
		templateProduct += '<span class="shoproductlistingid">'+prodItemId+'</span>';
		templateProduct += '<img src="'+shop.webSiteUrl+form.image.value+'" alt="'+prodItemId+'" />';
		templateProduct += '<span>'+(prodName.length < 24 ? prodName : prodName.substr(0,24)+'...')+'</span></a></li>';
		document.getElementById(shop.idProductList).innerHTML += templateProduct;
                msg.style.backgroundColor = 'green';
                msg.innerHTML = 'Product added.';
                msg.style.display = 'block';
                shop.resetFormAddProduct();
                var viewLink = document.getElementById(shop.idViewPage);
                viewLink.childNodes.item(1).href = (obj.url.length > 0 && typeof obj.url == 'string' ? shop.webSiteUrl+obj.url+'.html' : '#');
                viewLink.childNodes.item(1).setAttribute("onclick", "this.parentNode.style.display='none';");
                viewLink.style.display = 'block';
            } else {
                msg.style.backgroundColor = 'red';
                msg.innerHTML = "Can't add this product.";
                msg.style.display = 'block';
            }
        },
        error : function(statusText) {
            msg.style.backgroundColor = 'red';
            msg.innerHTML = 'Error: '+statusText;
            msg.style.display = 'block';
        }
    });
}
/*** method loads data product ***/
Shop.prototype.getDataProductForForm = function(prodid)
{
    document.getElementById(shop.idProductList).style.display = 'none';
    var productId = prodid;
    if (!/^([0-9]{1,10})$/.test(productId)) {return;}
    if (this.products == '') {
        this.getProducts();
    }
    this.ajax({
        type : 'POST',
        url : this.webSiteUrl+'sys/backend_shopping/getdataproduct/',
        data : {id : productId},
        success : function(data) {
            var product = eval('('+data+')');
            if (product.id > 0) {
                shop.resetFormAddProduct();
                document.getElementById('producttodel').value = productId;
                var form = document.forms[shop.formAddProduct];
                form.id.value = product.id;
                form.name.value = product.name;
                form.item_id.value = product.item_id;
                form.price.value = product.price;
                form.weight.value = product.weight;
                form.tax.value = product.tax;
                form.brand.value = product.brand;
                form.description.value = product.desc;
                if (product.photo != '') {
                    shop.selectImage(shop.webSiteUrl+product.photo);
                }
                if (product.options != '') {
                    shop.setOptions(product.options);
                }
                if (product.related != '') {
                   shop.setRelated(product.related);
                }
                if (product.groups != '') {
                    shop.setGroups(product.groups);
                }
                if (product.pageurl.length > 0 && typeof product.pageurl == 'string') {
                    var viewLink = document.getElementById(shop.idViewPage);
                    viewLink.childNodes.item(1).href = shop.webSiteUrl+product.pageurl+'.html';
                    viewLink.childNodes.item(1).removeAttribute('onclick');
                    viewLink.style.display = 'block';
                }
                document.getElementById(shop.idSubmitForm).setAttribute('onclick', 'shop.editProduct();');
            }
        }
    });
}
/*** method deletes product by id ***/
Shop.prototype.deleteProduct = function(productId)
{
    if (!/^([0-9]{1,10})$/.test(productId)) {return;}
    this.ajax({
        type : 'POST',
        url : this.webSiteUrl+'sys/backend_shopping/deleteproduct/',
        data : {id : productId},
        success : function(data) {
            var obj = eval('('+data+')');
            var msg = document.getElementById(shop.idMessage);
            if (obj.del) {
                msg.innerHTML = 'Product deleted.';msg.style.display = 'block';
                var elm = document.getElementById('prodlist').childNodes;
                for (var i=0; i<elm.length; i++) {
                    if (elm.item(i).id == productId) {
                        element = elm.item(i);
                        if (element != null) {
                            element.parentNode.removeChild(element)
                        }
                        break;
                    }
                }
                shop.resetFormAddProduct();
            } else {
                msg.innerHTML = "Can't delete this product.";msg.style.display = 'block';
            }
        }
    });
}
/*** method edits a product ***/
Shop.prototype.editProduct = function()
{
    var form = document.forms[this.formAddProduct];
    if (!/^([0-9]{1,10})$/.test(form.id.value) || form.id.value <= 0) {return;}
    if (!this.checkFormAddProduct()) {return;}
    var options = this.getOptions();
    var related = this.getRelated();
    var groups = this.getGroups();
    var msg = document.getElementById(this.idMessage);
    this.ajax({
        type : 'POST',
        url : this.webSiteUrl+'sys/backend_shopping/editproduct/',
        data : {id:form.id.value,name:form.name.value, item_id:form.item_id.value, price:form.price.value, weight:form.weight.value, tax:form.tax.options[form.tax.selectedIndex].value, photo:form.image.value,
            brand:form.brand.value, desc:form.description.value, options:options, related:related, groups:groups},
        success : function(data) {
            var obj = eval('('+data+')');
            if (obj.save) {
                msg.style.backgroundColor = 'green';
                msg.innerHTML = 'Product updated.';
                msg.style.display = 'block';
                var prodName = form.name.value;
                var prodItemId = form.item_id.value;
                prodName = prodName.replace(/^\s+/g,'');prodName = prodName.replace(/\s+$/g,'');
                prodItemId = prodItemId.replace(/^\s+/g,'');prodItemId = prodItemId.replace(/\s+$/g,'');
		var templateProduct = '<a href="#" onclick="shop.getDataProductForForm('+form.id.value+');">';
		templateProduct += '<span class="shoproductlistingid">'+prodItemId+'</span>';
		templateProduct += '<img src="'+shop.webSiteUrl+form.image.value+'" alt="'+prodItemId+'" />';
		templateProduct += '<span>'+(prodName.length < 24 ? prodName : prodName.substr(0,24)+'...')+'</span></a>';
                document.getElementById(form.id.value).innerHTML = templateProduct;
            } else {
                msg.style.backgroundColor = 'red';
                msg.innerHTML = "Can't update this product.";
                msg.style.display = 'block';
            }
        },
        error : function(statusText) {
            msg.style.backgroundColor = 'red';
            msg.innerHTML = 'Error: '+statusText;
            msg.style.display = 'block';
        }
    });
}
/*** method gets brands ***/
Shop.prototype.getBrands = function()
{    
    if (this.brands == '' || this.brands.length == 0) {
        this.ajax({
            type : 'POST',
            url : this.webSiteUrl+'sys/backend_shopping/getbrands/',
            success : function(data) {
                shop.brands = data.split(shop.separate);
            }
        });
    }
}
/*** method finds brand for 'autocomplete' ***/
Shop.prototype.autoCompleteBrand = function(elm)
{
    var val = elm.value;
    val = val.replace(/^\s+/g,'');
    val = val.replace(/\s+$/g,'');
    var ul = document.getElementById(this.idBrandsAutoComplete);
    ul.innerHTML = '';
    ul.style.display = 'none';
    if (val == '') {return;}
    for (var i in this.brands) {
        var brand = this.brands[i];
        var index = brand.toLowerCase().indexOf(val.toLowerCase());
        if (index == 0) {
            var li = document.createElement('li'), span = document.createElement('span');
            span.setAttribute('title', brand);span.innerHTML = brand.substr(0,18);
            li.appendChild(span);li.onclick = function() {elm.value = this.childNodes.item(0).title;};
            ul.appendChild(li);
        }
    }
    if (ul.childNodes.length > 0) {
        ul.style.display = 'block';
    }
}
/*** method edits a group ***/
Shop.prototype.editGroup = function(elm)
{
    var input = document.createElement('input');
    input.setAttribute('type', 'text');
    input.setAttribute('value', elm.title);
    input.setAttribute('style', 'width:65px;height:17px;padding:0;-moz-border-radius:0;color:#7c7c7c;font-size:12px;font-weight:normal;');
    input.addEventListener('keyup', function(e) {
        if (e == null) {
            keycode = event.keyCode;
        } else {
            keycode = e.which;
        }
        if (keycode == 13) {
            var name = this.value;
            name = name.replace(/^\s+/g,'');name = name.replace(/\s+$/g,'');
            if (name == '') {
                this.parentNode.innerHTML = this.parentNode.title.substr(0,8);return;
            }
            var id = this.parentNode.parentNode.getAttribute('id').split('-')[1];
            if (/^([0-9]{1,10})$/.test(id) && id > 0) {
                var textElm = this, parentElm = this.parentNode;
                shop.ajax({
                    type : 'POST',
                    url : shop.webSiteUrl+'sys/backend_shopping/editgroup/',
                    data : {id:id, name:name},
                    success : function(data) {
                        var obj = eval('('+data+')');
                        textElm.parentNode.removeChild(textElm);
                        if (obj.save) {
                            parentElm.title = name;
                            parentElm.innerHTML = name.substr(0,8);
                        } else {
                            parentElm.innerHTML = parentElm.title.substr(0,8);
                        }
                    }
                });
            } else {
                this.parentNode.innerHTML = this.parentNode.title.substr(0,8);
            }
        }
        if (keycode == 27) {
            this.parentNode.innerHTML = this.parentNode.title.substr(0,8);
        }
    }, false);
    elm.innerHTML = '';
    elm.appendChild(input);
}
/*** method filtering of products ***/
Shop.prototype.filterProductForProductList = function(val)
{
    val = val.replace(/^\s+/g,'');//val = val.replace(/\s+$/g,'');
    if (val == '') {
        document.getElementById(this.idProductList).innerHTML = '';
        var searchContent = '<li class="shoproductlisting" style="height:30px;width:720px;font-size:16px;font-weight:bold;">';
        searchContent += 'Search: <input type="text" name="filterproduct" id="filterproduct" value="'+val+'" style="color:#7c7c7c;" onfocus="shop.getProducts();" onkeyup="shop.filterProductForProductList(this.value);"></li>';
        document.getElementById(this.idProductList).innerHTML = searchContent;
        for (var i in this.products) {
            var dataProduct = this.products[i].split(':::');
            if (dataProduct.length  == 4) {
                this.addElementProductForProductList(dataProduct);
            }
        }
        document.getElementById("filterproduct").focus();
    } else {
        document.getElementById(this.idProductList).innerHTML = '';
        var searchContent = '<li class="shoproductlisting" style="height:30px;width:720px;font-size:16px;font-weight:bold;">';
        searchContent += 'Search: <input type="text" name="filterproduct" id="filterproduct" value="'+val+'" style="color:#7c7c7c;" onfocus="shop.getProducts();" onkeyup="shop.filterProductForProductList(this.value);"></li>';
        document.getElementById(this.idProductList).innerHTML = searchContent;
        for (var i in this.products) {
            var dataProduct = this.products[i].split(':::');
            var index = dataProduct[0].toLowerCase().indexOf(val.toLowerCase());
            if (index == 0) {
                this.addElementProductForProductList(dataProduct);
            }
        }
        document.getElementById("filterproduct").focus();
    }
}
/*** method adds content for product ***/
Shop.prototype.addElementProductForProductList = function(dataProduct)
{
    var elmLI = document.createElement("LI");
    elmLI.setAttribute("class", "shoproductlisting");
    elmLI.setAttribute("id", dataProduct[2]);
    var elmA = document.createElement("A");
    elmA.setAttribute("href", "#");
    elmA.setAttribute("onclick", "shop.getDataProductForForm('"+dataProduct[2]+"')");
    var elmSPAN1 = document.createElement("SPAN");
    elmSPAN1.setAttribute("class", "shoproductlistingid");
    elmSPAN1.innerHTML = dataProduct[3];
    var elmIMG = document.createElement("IMG");
    elmIMG.setAttribute("src", this.webSiteUrl+dataProduct[1]);
    elmIMG.setAttribute("alt", dataProduct[3]);
    var elmSPAN2 = document.createElement("SPAN");
    elmSPAN2.innerHTML = (dataProduct[0].length < 24 ? dataProduct[0] : dataProduct[0].substr(0,24)+'...');
    elmA.appendChild(elmSPAN1);elmA.appendChild(elmIMG);elmA.appendChild(elmSPAN2);
    elmLI.appendChild(elmA);
    document.getElementById(this.idProductList).appendChild(elmLI);
}

var shop = new Shop();